package com.zhangkunhao.notes.service;


import com.zhangkunhao.notes.dao.QuestionDao;
import com.zhangkunhao.notes.entity.Do.*;
import com.zhangkunhao.notes.entity.bo.Message;

import com.zhangkunhao.notes.entity.bo.PageBean;
import com.zhangkunhao.notes.entity.bo.PostPageBean;


import com.zhangkunhao.notes.dao.UserDao;


import com.zhangkunhao.notes.service.impl.UserService;
import com.zhangkunhao.notes.utils.EmailCheckUtil;
import com.zhangkunhao.notes.utils.IfValidInputUtil;
import com.zhangkunhao.notes.utils.PasswordStrengthUtil;

import java.sql.SQLException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 20642
 * @description TODO
 * @date 2023/4/9 15:01
 */
public class UserServiceImpl implements UserService {
    @Override
    public List<User> selectAll() {
        return UserDao.getInstance().findAll();
    }

    @Override
    public void insert(User user) throws Exception {
        UserDao.getInstance().insert(user);
    }

    @Override
    public int delete(int id) throws SQLException {
        return UserDao.getInstance().delete(id);
    }

    @Override
    public int update(User user, String... params) throws Exception {
        return UserDao.getInstance().update(user);
    }


    public Message<User> login(User user) {

        System.out.println("登录的对象 " + user);

        Message<User> loginMessage = new Message<>();
        // 初始化失败的标识
        loginMessage.setT(null);
        loginMessage.setStatus(0);
        if (user == null) {
            loginMessage.setResult("当前用户为空");
            return loginMessage;
        } else {
            if (!(IfValidInputUtil.ifValidValue(user.getEmail()))) {
                loginMessage.setResult("当前邮箱为空");
                return loginMessage;
            }
            if (!(IfValidInputUtil.ifValidValue(user.getPassword()))) {
                loginMessage.setResult("当前密码为空");
                return loginMessage;
            }
            if (!(IfValidInputUtil.emptyCheckPass(user.getEmail()))) {
                loginMessage.setResult("当前邮箱出现空格");
                return loginMessage;
            }
            if (!(IfValidInputUtil.emptyCheckPass(user.getPassword()))) {
                loginMessage.setResult("当前密码出现空格");
                return loginMessage;
            }
        }

        // 调用service查询
        List<User> users = this.selectAll();

        for (User user2 : users) {
            if (user2 != null) {
                if (user2.getEmail().equals(user.getEmail()) && user2.getPassword().equals(user.getPassword())) {
                    // 响应成功的标识，更改状态码和返回对象
                    loginMessage.setStatus(1);
                    loginMessage.setT(user2);
                    loginMessage.setResult("用户邮箱:" + user2.getEmail() + "登录成功");
                    System.out.println("loginSuccess-----");
                    return loginMessage;
                }
            }
        }

        // 响应失败的标识
        System.out.println("loginFailed-----");
        loginMessage.setResult("邮箱或密码错误");
        return loginMessage;
    }

    public Message<User> register(User user) throws Exception {

        System.out.println("注册的对象 " + user);
        Message<User> registerMessage = new Message<>();

        // 初始化失败的标识
        registerMessage.setT(null);
        registerMessage.setStatus(0);
        if (user == null) {
            registerMessage.setResult("当前用户为空");
            return registerMessage;
        } else {
            if (!(IfValidInputUtil.ifValidValue(user.getEmail()))) {
                registerMessage.setResult("当前邮箱为空");
                return registerMessage;
            }
            if (!(IfValidInputUtil.ifValidValue(user.getPassword()))) {
                registerMessage.setResult("当前密码为空");
                return registerMessage;
            }
            if (!(IfValidInputUtil.emptyCheckPass(user.getEmail()))) {
                registerMessage.setResult("当前邮箱出现空格");
                return registerMessage;
            }
            if (!(IfValidInputUtil.emptyCheckPass(user.getPassword()))) {
                registerMessage.setResult("当前密码出现空格");
                return registerMessage;
            }
        }

        //正则表达式校验邮箱
        if (!EmailCheckUtil.isValidEmail(user.getEmail())) {
            registerMessage.setResult("邮箱格式错误，其正确格式：前缀必须由字母、数字、下划线、连字符和点号等组成长度至少为1的字符串" +
                    "，并且后缀为@qq.com、@163.com或@123.com 中的一个");
            System.out.println("Email " + user.getEmail() + " is valid: " + EmailCheckUtil.isValidEmail(user.getEmail()));
            return registerMessage;
        }

        //正则表达式校验密码强度
        if (!PasswordStrengthUtil.isValidPassword(user.getPassword())) {
            registerMessage.setResult("密码格式错误，密码不能包含空格，必须包含大、小写字母、数字，" +
                    "可以包含除中文外的任意字符，总长度大于等于6");
            System.out.println("password" + user.getPassword() + "is valid" + PasswordStrengthUtil.isValidPassword(user.getPassword()));
            return registerMessage;
        }


        // 调用service查询
        List<User> users = this.selectAll();

        for (User user2 : users) {
            if (user2 != null) {
                if (user2.getEmail().equals(user.getEmail())) {
                    // 响应失败的标识
                    System.out.println("registerFailed-----");
                    registerMessage.setResult("当前邮箱已经注册过，请直接登录");
                    return registerMessage;
                }
            }
        }
        //调用dao
        this.insert(user);

        //调用dao更新数据
        users = this.selectAll();

        for (User user3 : users) {
            if (user3 != null) {
                if (user3.getEmail().equals(user.getEmail())) {
                    // 响应成功的标识，更改状态码和返回对象
                    System.out.println("registerSuccess");
                    registerMessage.setResult("用户邮箱:" + user3.getEmail() + "注册成功");
                    registerMessage.setT(user3);
                    registerMessage.setStatus(1);
                    break;
                }
            }
        }
        return registerMessage;
    }

    public Message<User> forgetPassword(User user) throws Exception {
        // 初始化失败的标识
        Message<User> updatePasswordMessage = new Message<>(null, "找不到该邮箱", 0);

        if (user == null) {
            updatePasswordMessage.setResult("当前用户为空");
            return updatePasswordMessage;
        } else {
            if (!(IfValidInputUtil.ifValidValue(user.getEmail()))) {
                updatePasswordMessage.setResult("当前邮箱为空");
                return updatePasswordMessage;
            }
            if (!(IfValidInputUtil.ifValidValue(user.getPassword()))) {
                updatePasswordMessage.setResult("当前密码为空");
                return updatePasswordMessage;
            }
            if (!(IfValidInputUtil.emptyCheckPass(user.getEmail()))) {
                updatePasswordMessage.setResult("当前邮箱出现空格");
                return updatePasswordMessage;
            }
            if (!(IfValidInputUtil.emptyCheckPass(user.getPassword()))) {
                updatePasswordMessage.setResult("当前密码出现空格");
                return updatePasswordMessage;
            }
        }

        //正则表达式校验邮箱
        if (!EmailCheckUtil.isValidEmail(user.getEmail())) {
            updatePasswordMessage.setResult("邮箱格式错误，其正确格式：前缀必须由字母、数字、下划线、连字符和点号等组成长度至少为1的字符串" +
                    "，并且后缀为@qq.com、@163.com或@123.com 中的一个");
            System.out.println("Email " + user.getEmail() + " is valid: " + EmailCheckUtil.isValidEmail(user.getEmail()));
            return updatePasswordMessage;
        }

        //正则表达式校验密码强度
        if (!PasswordStrengthUtil.isValidPassword(user.getPassword())) {
            updatePasswordMessage.setResult("密码格式错误，密码不能包含空格，必须包含大、小写字母、数字，" +
                    "可以包含除中文外的任意字符，总长度大于等于6");
            System.out.println("password" + user.getPassword() + "is valid" + PasswordStrengthUtil.isValidPassword(user.getPassword()));
            return updatePasswordMessage;
        }

        // 调用service查询
        List<User> users = this.selectAll();

        for (User user2 : users) {
            if (user2 != null) {
                if (user2.getEmail().equals(user.getEmail())) {
                    // 响应成功的标识，更改状态码和返回对象
                    user2.setPassword(user.getPassword());
                    //调用dao
                    this.update(user2);
                    System.out.println("updatePasswordSuccess-----");
                    updatePasswordMessage.setT(user2);
                    updatePasswordMessage.setStatus(1);
                    updatePasswordMessage.setResult("用户邮箱:" + user.getEmail() + "修改密码成功，请登录");
                    return updatePasswordMessage;
                }
            }
        }
        return updatePasswordMessage;
    }

    public PostPageBean showPost() {
        //调用service层,要过滤
        QuestionServiceImpl questionServiceImpl = new QuestionServiceImpl();
        List<Question> questionList = questionServiceImpl
                .selectAll().stream()
                .filter(question -> question.getCheckStatus() == 1)
                .filter(question -> question.getReportStatus() == 1)
                .sorted((o1, o2) -> o2.getLaunchTime().compareTo(o1.getLaunchTime()))
                .collect(Collectors.toList());
        //
        AnswerServiceImpl answerServiceImpl = new AnswerServiceImpl();
        List<Answer> answerList = answerServiceImpl.selectAll();
        //
        AnswerCommentServiceImpl answerCommentServiceImpl = new AnswerCommentServiceImpl();
        List<AnswerComment> answerCommentList = answerCommentServiceImpl.selectAll().stream()
                .filter(answerComment -> answerComment.getReportStatus() == 1)
                .collect(Collectors.toList());

        if (questionList != null) {
            return new PostPageBean(questionList.size(), questionList, answerList, answerCommentList);
        } else {
            return new PostPageBean(0, questionList, answerList, answerCommentList);
        }
    }

    public PostPageBean selectByPage(int currentPage, int pageSize) {
        //1.获取总查询记录的数量
        int allCount = QuestionDao.getInstance().findAll().size();

        //2.计算当前开始索引
        int begin = (currentPage - 1) * pageSize;

        //3.获取当前页面查询得到的数据集合
        List<Question> pageRows = QuestionDao.getInstance()
                .findAll(" limit " + begin + "," + pageSize)
                .stream().filter(question -> question.getCheckStatus() == 1 && question.getReportStatus() == 1)
                .sorted((o1, o2) -> o2.getLaunchTime().compareTo(o1.getLaunchTime())).collect(Collectors.toList());

        List<Answer> answers = new AnswerServiceImpl().selectAll();

        List<AnswerComment> answerComments = new AnswerCommentServiceImpl()
                .selectAll()
                .stream()
                .filter(answerComment -> answerComment.getReportStatus() == 1)
                .collect(Collectors.toList());

        //4.封装PageBean对象
        PostPageBean postPageBean = new PostPageBean(allCount, pageRows, answers, answerComments);
        return postPageBean;
    }

    public PostPageBean rankQuestionByLikesCount() {
        //调用service层
        QuestionServiceImpl questionServiceImpl = new QuestionServiceImpl();
        //排序,要过滤
        List<Question> questionList = questionServiceImpl.selectAll()
                .stream().filter(question -> question.getCheckStatus() == 1 && question.getReportStatus() == 1)
                .sorted((o1, o2) -> o2.getLikeCount() - o1.getLikeCount())
                .collect(Collectors.toList());

        AnswerServiceImpl answerServiceImpl = new AnswerServiceImpl();
        List<Answer> answerList = answerServiceImpl.selectAll();
        //
        AnswerCommentServiceImpl answerCommentServiceImpl = new AnswerCommentServiceImpl();
        List<AnswerComment> answerCommentList = answerCommentServiceImpl.selectAll().stream()
                .filter(answerComment -> answerComment.getReportStatus() == 1)
                .collect(Collectors.toList());

        if (questionList != null) {
            return new PostPageBean(questionList.size(), questionList, answerList, answerCommentList);
        } else {
            return new PostPageBean(0, questionList, answerList, answerCommentList);
        }
    }

    public Message<User> editProfile(User user) throws Exception {
        Message<User> userMessage = new Message<>(null, "修改个人信息失败", 0);

        if (user == null) {
            userMessage.setResult("当前用户为空,修改个人信息失败");
            return userMessage;
        } else {
            if (!(IfValidInputUtil.ifValidValue(user.getUserName()))) {
                userMessage.setResult("当前用户名为空");
                return userMessage;
            }
            if (!(IfValidInputUtil.ifValidValue(user.getGender()))) {
                userMessage.setResult("当前性别为空");
                return userMessage;
            }
        }
        //调用dao
        int update = this.update(user);

        //成功
        if (update > 0) {
            userMessage.setResult("修改个人信息成功，已刷新用户数据");
            userMessage.setStatus(1);
            userMessage.setT(user);
        }

        return userMessage;
    }

    public Message<User> updatePassword(String oldPassword, String newPassword, int userId) throws Exception {
        Message<User> userMessage = new Message<>(null, "修改密码失败", 0);

        if (!(IfValidInputUtil.ifValidValue(oldPassword))) {
            userMessage.setResult("当前旧密码为空");
            return userMessage;
        }
        if (!(IfValidInputUtil.ifValidValue(newPassword))) {
            userMessage.setResult("当前新密码为空");
            return userMessage;
        }

        //查询
        User user = this.selectAll().stream()
                .filter(user1 -> user1.getId().equals(userId)).collect(Collectors.toList()).get(0);

        if (user.getPassword().equals(oldPassword)) {

            if (!PasswordStrengthUtil.isValidPassword(newPassword)) {
                userMessage.setResult("密码格式错误，密码不能包含空格，必须包含大、小写字母、数字，" +
                        "可以包含除中文外的任意字符，总长度大于等于6");
                return userMessage;
            }
        } else {
            userMessage.setResult("校验原密码错误，请重试");
            return userMessage;
        }
        //修改
        user.setPassword(newPassword);
        //调用dao
        int update = this.update(user);

        //成功
        if (update > 0) {
            userMessage.setResult("修改密码成功，已刷新用户数据");
            userMessage.setStatus(1);
            userMessage.setT(user);
        }

        return userMessage;
    }

    public PageBean<User> searchUser(String myInterestedUser) {
        PageBean<User> userPageBean = new PageBean<>(0, null);
        //校验
        if ((!IfValidInputUtil.ifValidValue(myInterestedUser)) || (!IfValidInputUtil.emptyCheckPass(myInterestedUser))) {
            return userPageBean;
        }
        List<User> searchUsers = UserDao.getInstance()
                .findAll(" where user_name like '%" + myInterestedUser + "%'");
//                .findAll("user_name", myInterestedUser);
        if (searchUsers.size() > 0) {
            userPageBean.setRows(searchUsers);
            userPageBean.setTotalCount(searchUsers.size());
        }
        return userPageBean;
    }


    public Message<User> updatePicture(int userId, String imagePath) throws Exception {
        //初始化
        Message<User> updatePictureMessage = new Message<>();
        updatePictureMessage.setStatus(0);
        updatePictureMessage.setT(null);
        updatePictureMessage.setResult("修改头像失败");

        //修改
        List<User> nowUser = this.selectAll().stream().filter(user -> user.getId().equals(userId)).collect(Collectors.toList());
        User user = nowUser.get(0);
        user.setImagePath(imagePath);

        //调用dao
        int update = this.update(user);

        user = this.selectAll().stream().filter(user1 -> user1.getId().equals(userId)).collect(Collectors.toList()).get(0);

        if (update > 0) {
            updatePictureMessage.setResult("修改头像成功");
            updatePictureMessage.setStatus(1);
            updatePictureMessage.setT(user);
        }
        return updatePictureMessage;

    }

    public Message<User> showUser(int userId) {
        //初始化
        Message<User> showUserMessage = new Message<>(null, "用户数据刷新失败", 0);

        //查询
        User user = this.selectAll().stream().filter(user1 -> user1.getId().equals(userId)).collect(Collectors.toList()).get(0);

        //返回controller
        if (user != null) {
            showUserMessage.setResult("用户数据刷新成功");
            showUserMessage.setStatus(1);
            showUserMessage.setT(user);
        }
        System.out.println("sercvice层的user:" + user);
        return showUserMessage;
    }

    public PageBean<User> listUsers() {
        // 调用dao查询所有的用户
        List<User> users = this.selectAll();

        //初始化
        if (users != null && users.size() > 0) {
            //返回数据
            PageBean<User> userPageBean = new PageBean<>(users.size(), users);
            return userPageBean;
        } else {
            return new PageBean(0, null);
        }

    }

    public Message<User> banUser(int banUserId) throws Exception {
        //初始化
        Message<User> userMessage = new Message<>(null, "封禁该用户失败", 0);
        User user = this.selectAll().stream().filter(user1 -> user1.getId().equals(banUserId)).collect(Collectors.toList()).get(0);
        if (user != null) {
            user.setActivationStatus(0);
        } else {
            userMessage.setResult("该用户不存在");
            return userMessage;
        }
        //调用dao
        int update = this.update(user);

        //成功
        if (update > 0) {
            userMessage.setResult("封禁该用户成功");
            userMessage.setStatus(1);
            userMessage.setT(user);
        }

        return userMessage;
    }

    public Message<User> cancelBanUser(int cancelBanUserId) throws Exception {

        //初始化
        Message<User> userMessage = new Message<>(null, "取消封禁失败", 0);
        User user = this.selectAll().stream().filter(user1 -> user1.getId().equals(cancelBanUserId)).collect(Collectors.toList()).get(0);
        if (user != null) {
            user.setActivationStatus(1);
        } else {
            userMessage.setResult("该用户不存在");
            return userMessage;
        }
        //调用dao
        int update = this.update(user);

        //成功
        if (update > 0) {
            userMessage.setResult("取消封禁成功");
            userMessage.setStatus(1);
            userMessage.setT(user);
        }
        return userMessage;
    }

}
